package com.hsl.housaileibot001.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hsl.housaileibot001.common.PageRequest;
import com.hsl.housaileibot001.common.PageResult;
import com.hsl.housaileibot001.mapper.PracticeRecordMapper;
import com.hsl.housaileibot001.mapper.WrongQuestionMapper;
import com.hsl.housaileibot001.model.PracticeRecord;
import com.hsl.housaileibot001.model.WrongQuestion;
import com.hsl.housaileibot001.model.dto.PracticeRecordDTO;
import com.hsl.housaileibot001.model.vo.PracticeRecordVO;
import com.hsl.housaileibot001.service.PracticeRecordService;
import com.hsl.housaileibot001.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 答题记录服务实现类
 */
@Slf4j
@Service
public class PracticeRecordServiceImpl implements PracticeRecordService {

    @Autowired
    private PracticeRecordMapper practiceRecordMapper;

    @Autowired
    private WrongQuestionMapper wrongQuestionMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private com.hsl.housaileibot001.service.UserService userService;

    @Override
    @Transactional
    public void submitRecord(PracticeRecordDTO recordDTO) {
        // 获取当前用户ID
        // Long userId = getCurrentUserId();
        Long userId = 1988521939104763905L;
        // 创建答题记录
        PracticeRecord record = new PracticeRecord();
        record.setUserId(userId);
        record.setQuestionId(recordDTO.getQuestionId());
        record.setInterviewQuestionId(recordDTO.getInterviewQuestionId());
        record.setUserAnswer(recordDTO.getUserAnswer());
        record.setIsCorrect(recordDTO.getIsCorrect());
        record.setPracticeTime(LocalDateTime.now());
        record.setCreatedTime(LocalDateTime.now());
        record.setUpdatedTime(LocalDateTime.now());
        record.setDeleted(false);
        record.setVersion(1);

        practiceRecordMapper.insert(record);

        // 如果答错，自动添加到错题本
        if (Boolean.FALSE.equals(recordDTO.getIsCorrect())) {
            addToWrongQuestion(userId, recordDTO.getQuestionId(), recordDTO.getInterviewQuestionId());
        }

        log.info("保存答题记录成功: userId={}, questionId={}, isCorrect={}", userId, recordDTO.getQuestionId(), recordDTO.getIsCorrect());
    }

    @Override
    public PageResult<PracticeRecordVO> getRecords(PageRequest pageRequest) {
        Long userId = getCurrentUserId();

        // 构建查询条件
        LambdaQueryWrapper<PracticeRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PracticeRecord::getUserId, userId);
        wrapper.eq(PracticeRecord::getDeleted, false);
        wrapper.orderByDesc(PracticeRecord::getPracticeTime);

        // 分页查询
        Page<PracticeRecord> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        Page<PracticeRecord> result = practiceRecordMapper.selectPage(page, wrapper);

        // 转换为VO
        List<PracticeRecordVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        PageResult<PracticeRecordVO> pageResult = new PageResult<>();
        pageResult.setRecords(voList);
        pageResult.setTotal(result.getTotal());
        pageResult.setSize((long) result.getSize());
        pageResult.setCurrent(result.getCurrent());

        return pageResult;
    }

    @Override
    public Map<String, Object> getStats() {
        Long userId = getCurrentUserId();

        // 构建查询条件
        LambdaQueryWrapper<PracticeRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PracticeRecord::getUserId, userId);
        wrapper.eq(PracticeRecord::getDeleted, false);

        // 查询总数
        long total = practiceRecordMapper.selectCount(wrapper);

        // 查询正确数
        wrapper.eq(PracticeRecord::getIsCorrect, true);
        long correct = practiceRecordMapper.selectCount(wrapper);

        // 计算正确率
        double accuracy = total > 0 ? (double) correct / total * 100 : 0;

        Map<String, Object> stats = new HashMap<>();
        stats.put("total", total);
        stats.put("correct", correct);
        stats.put("wrong", total - correct);
        stats.put("accuracy", Math.round(accuracy * 100.0) / 100.0);

        return stats;
    }

    /**
     * 添加到错题本
     */
    private void addToWrongQuestion(Long userId, String questionId, Long interviewQuestionId) {
        // 查找是否已存在
        LambdaQueryWrapper<WrongQuestion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WrongQuestion::getUserId, userId);
        wrapper.eq(WrongQuestion::getQuestionId, questionId);
        wrapper.eq(WrongQuestion::getDeleted, false);
        WrongQuestion wrongQuestion = wrongQuestionMapper.selectOne(wrapper);

        if (wrongQuestion == null) {
            // 创建新错题记录
            wrongQuestion = new WrongQuestion();
            wrongQuestion.setUserId(userId);
            wrongQuestion.setQuestionId(questionId);
            wrongQuestion.setInterviewQuestionId(interviewQuestionId);
            wrongQuestion.setWrongCount(1);
            wrongQuestion.setLastWrongTime(LocalDateTime.now());
            wrongQuestion.setCreatedTime(LocalDateTime.now());
            wrongQuestion.setUpdatedTime(LocalDateTime.now());
            wrongQuestion.setDeleted(false);
            wrongQuestion.setVersion(1);
            wrongQuestionMapper.insert(wrongQuestion);
        } else {
            // 更新错误次数
            wrongQuestion.setWrongCount(wrongQuestion.getWrongCount() + 1);
            wrongQuestion.setLastWrongTime(LocalDateTime.now());
            wrongQuestion.setUpdatedTime(LocalDateTime.now());
            wrongQuestionMapper.updateById(wrongQuestion);
        }
    }

    /**
     * 转换为VO
     */
    private PracticeRecordVO convertToVO(PracticeRecord record) {
        PracticeRecordVO vo = new PracticeRecordVO();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("用户未登录");
        }
        String username = authentication.getName();
        com.hsl.housaileibot001.model.vo.UserInfoVO userInfo = userService.getCurrentUser();
        return userInfo.getId();
    }
}

